package com.susallwave.srcb.schedule;

import com.susallwave.srcb.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public abstract class RetryDistributedLock {

    @Autowired
    private RedisUtil redisUtil;

    protected abstract String taskName();

    protected abstract void doBusiness() throws Exception;

    public String run() {
        String lockKey = "lock:" + taskName();
        if (redisUtil.tryLock(lockKey, 300)) {
            log.info("【{}】获得锁，开始执行", taskName());
            try {
                int maxRetry = 3;
                for (int i = 1; i <= maxRetry; i++) {
                    try {
                        log.info("【{}】第 {} 次尝试", taskName(), i);
                        doBusiness();
                        log.info("【{}】执行成功", taskName());
                        return "SUCCESS";
                    } catch (Exception e) {
                        log.error("【{}】失败：{}", taskName(), e.getMessage());
                        if (i == maxRetry) {
                            log.error("【{}】重试次数用尽", taskName());
                            return "FAILED";
                        }
                    }
                }
            } finally {
                redisUtil.delete(lockKey);
                log.info("【{}】释放锁", taskName());
            }
        } else {
            log.warn("【{}】跳过执行：未获得锁", taskName());
            return "SKIPPED";
        }
        return "FAILED";
    }
}
